﻿using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Fleck;

namespace CSharp_WebSocket_Demo
{
    class Program
    {

        static void Main(string[] args)
        {
            //服务器地址
            string ip = "127.0.0.1";
            //服务端口
            int port = 80;

            //多线程安全的字典，存储客户端
            //键：客户端ip:port
            //值：客户端对象
            ConcurrentDictionary<string, IWebSocketConnection> webSocketConnectionDictionary = new ConcurrentDictionary<string, IWebSocketConnection>();

            //服务端
            WebSocketServer webSocketServer = new WebSocketServer($"ws://{ip}:{port}");

            //出错后自动重启
            webSocketServer.RestartAfterListenError = true;

            //开启服务
            webSocketServer.Start(socket =>
            {
                string key = socket.ConnectionInfo.ClientIpAddress + ":" + socket.ConnectionInfo.ClientPort;

                //客户端连接上事件
                socket.OnOpen = () =>
                {
                    Console.WriteLine($"客户端【{key}】连接上服务器");
                    //尝试添加到字典中
                    webSocketConnectionDictionary.TryAdd(key, socket);
                    Console.WriteLine($"当前客户端连接数:{webSocketConnectionDictionary.Count}");
                };

                //服务关闭事件
                socket.OnClose = () =>
                {
                    Console.WriteLine($"客户端【{key}】断开连接");
                    //尝试从字典中移除
                    webSocketConnectionDictionary.TryRemove(key, out _);
                    Console.WriteLine($"当前客户端连接数:{webSocketConnectionDictionary.Count}");
                };

                //服务器出错事件
                socket.OnError = (Exception e) =>
                {
                    Console.WriteLine($"客户端【{key}】连接出错");
                    //尝试从字典中移除
                    webSocketConnectionDictionary.TryRemove(key, out _);
                    Console.WriteLine($"当前客户端连接数:{webSocketConnectionDictionary.Count}");
                };

                //服务器接到客户端消息事件
                socket.OnMessage = (string msg) =>
                {
                    Console.WriteLine($"客户端【{key}】发来消息:{msg}");

                    //给所有客户端返回该消息，实现聊天功能
                    foreach (IWebSocketConnection webSocketConnection in webSocketConnectionDictionary.Values)
                    {
                        try
                        {
                            webSocketConnection.Send($"【{key}】:msg");
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine($"尝试给{webSocketConnection.ConnectionInfo.ClientIpAddress}:{webSocketConnection.ConnectionInfo.ClientPort}发送消息发生异常");
                            Console.WriteLine(e.StackTrace);
                        }
                    }
                };
            });

            Console.WriteLine($"服务端开启 ws://{ip}:{port}");

            //防止程序一闪而过
            Console.ReadKey();
        }
    }
}
